package com.jinyi.wwdeng.ui.steps.act

import android.annotation.SuppressLint
import android.content.Intent
import android.view.Gravity
import android.view.View
import com.jinyi.base.network.NetworkUtils
import com.jinyi.base.utils.img.ImageUtil
import com.jinyi.base.utils.log.HHLog
import com.jinyi.lib_http.callback.StringCallback
import com.jinyi.lib_http.model.Progress
import com.jinyi.lib_http.model.Response
import com.jinyi.lib_http.request.base.Request
import com.jinyi.wwdeng.AppConfigs
import com.jinyi.wwdeng.R
import com.jinyi.wwdeng.databinding.ActOcrUploadBinding
import com.jinyi.wwdeng.network.ApiService
import com.jinyi.wwdeng.pro.ProAct
import com.jinyi.wwdeng.ui.user.act.UserFeedbackAct
import com.jinyi.wwdeng.utils.event.TrackEventType
import com.jinyi.wwdeng.utils.event.TrackEventUtils
import org.json.JSONObject
import java.io.File

/**
 * JinYiTest
 * @Author wwdeng
 * @CreateTime: 2024/4/22 19:25
 * @Annotation：图片上传页面
 */
class OcrUploadAct: ProAct(){

    lateinit var binding: ActOcrUploadBinding
    //上传完成的图片地址
    var imgUrl = ""

    companion object{
        const val KEY_FILE_PATH = "filePath"//文件路径
        const val KEY_CONTENT_TYPE = "contentType"//1相机  2相册
        const val KEY_ORC_TYPE = "orcType"//证件类型  1身份证  2护照  3驾驶证
        const val KEY_ORC_FRONT = "orcFront"//照片正面
    }

    override fun getRootView(): View {
        binding = ActOcrUploadBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        setTitleBarVisibility(View.VISIBLE)
        setTextTitle(getString(R.string.uploading))
        setTextTitleGravity(Gravity.CENTER)
        setRightBtnRes(R.mipmap.pic_kefu_black_icon)
    }

    override fun initListener() {
        //联系客服
        rootViewBinding.ivFun.setOnClickListener {
            onIntent(UserFeedbackAct::class.java)
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_CUSTOMER,"OcrUpload ${getOcrTypeString()} Page")
        }
        //使用照片
        binding.btnUsePhoto.setOnClickListener {
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_STEP_OCR_UPLOAD_USE_PHOTO,getOcrTypeString()+"：" + imgUrl)
            //发送广播，传回图片地址和正反类型
            val result = JSONObject()
            result.put("imgUrl",imgUrl)
            result.put("imgPath",getFilePath())
            result.put("isFront",getOcrFront())
            val intent = Intent(AppConfigs.Action.ACTION_UPLOAD_USE)
            intent.putExtra("imgData",result.toString())
            sendBroadcast(intent)
            finish()
        }

        //重新获取
        binding.btnRetake.setOnClickListener {
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_STEP_OCR_UPLOAD_RETAKE,getOcrTypeString()+"：" + imgUrl)
            val file = File(getFilePath())
            if (file.isFile){
                file.delete()
            }
            finish()
        }
    }

    override fun initData() {
        ImageUtil.getInstance().loadImage(this,binding.ivImage,getFilePath())

        HHLog.e("文件路径："+getFilePath())
        HHLog.e("Orc类型："+getOcrType())
        HHLog.e("Orc正反："+getOcrFront())
        //显示上传中状态
        showUploadingView()
        showLoading("",false,true)
        uploadImageAction()
    }

    /**
     * 获取文件路径
     */
    private fun getFilePath(): String{
        val bundle = intent.extras
        if (bundle != null){
            return bundle.getString(KEY_FILE_PATH,"")
        }
        return ""
    }

    /**
     * 获取证件类型  1身份证  2护照  3驾驶证
     */
    private fun getOcrType(): Int{
        val bundle = intent.extras
        if (bundle != null){
            return bundle.getInt(KEY_ORC_TYPE,1)
        }
        return 1
    }

    /**
     * 获取正反面
     */
    private fun getOcrFront(): Boolean{
        val bundle = intent.extras
        if (bundle != null){
            return bundle.getBoolean(KEY_ORC_FRONT,true)
        }
        return true
    }

    /**
     * 获取证件类型
     * IdCard  Passport DriverLicense
     */
    private fun getOcrTypeString(): String{
        when(getOcrType()){
            1 -> {
                return "IdCard"
            }
            2 -> {
                return "Passport"
            }
            else -> {
                return "DriverLicense"
            }
        }
    }

    /**
     * 上传中状态
     */
    private fun showUploadingView(){
        binding.tvProgress.visibility = View.VISIBLE
        binding.ivConfirm.visibility = View.GONE
        binding.btnRetake.alpha = 0.5f
        binding.btnRetake.isEnabled = false
        binding.btnUsePhoto.alpha = 0.5f
        binding.btnUsePhoto.isEnabled = false
    }

    /**
     * 上传完成
     */
    private fun showUploadCompleteView(){
        binding.tvProgress.visibility = View.GONE
        binding.ivConfirm.visibility = View.VISIBLE
        binding.btnRetake.alpha = 1f
        binding.btnRetake.isEnabled = true
        binding.btnUsePhoto.alpha = 1f
        binding.btnUsePhoto.isEnabled = true
    }

    //上传图片
    private fun uploadImageAction(){
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.API_UPLOAD_FILE_URL)
        NetworkUtils.uploadFile(httpUrl,getFilePath(),object : StringCallback(){
            override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
                HHLog.e("正在上传中...")
            }

            override fun onSuccess(response: Response<String>?) {
                HHLog.e("上传完成："+response!!.body())
                if (response!!.code() == 200){
                    val data = JSONObject(response!!.body())
                    when(data.optInt("code")){
                        0 -> {//成功
                            imgUrl = data.optJSONObject("obj")!!.optString("url")
                            showUploadCompleteView()
                        }
                        else -> {
                            val msg = data.optString("msg")
                            showToast(msg)
                        }
                    }
                } else {
                    showToast(response!!.message())
                }
            }

            override fun onError(response: Response<String>?) {
                HHLog.e("上传出错"+response!!.body())
                showToast(response.message())
            }

            @SuppressLint("SetTextI18n")
            override fun uploadProgress(progress: Progress) {
                HHLog.e("正在上传中，uploadProgress: $progress")
                HHLog.e("正在上传中，文件总大小: ${progress.totalSize}")
                HHLog.e("正在上传中，当前进度: ${progress.currentSize}")

                val totalSize = progress.totalSize
                val currentSize = progress.currentSize

                binding.progressBar.max = totalSize.toInt()
                binding.progressBar.progress = currentSize.toInt()
                binding.tvProgress.text = ((currentSize / totalSize) * 100).toString()+"%"
            }

            override fun onFinish() {
                hideLoading()
            }
        })
    }

    override fun onStart() {
        super.onStart()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_STEP_OCR_UPLOAD_START,getOcrTypeString())
    }

    override fun onDestroy() {
        super.onDestroy()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_STEP_OCR_UPLOAD_END,getOcrTypeString())
    }
}